﻿using UnityEngine;
using System.Collections;
namespace UnityExtension
{
	public static class GameObjectUtility
	{
		/// <summary>
		/// 取得当前对象的某个组件 如果不存在 就添加!
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="ojb"></param>
		/// <returns>如果ojb为null就返回null</returns>
		public static T GetComponentOrAdd<T>(this GameObject self) where T : Component, new()
		{
			if(self != null)
			{
				T t = self.GetComponent<T>();
				if(t == null)
				{
					t = self.AddComponent<T>();
				}
				return t;
			}
			return null;
		}
		public static GameObject FindChild(this GameObject self,string childname)
		{
			var child = self.transform.FindChild(childname);
			if(child == null)
			{
				return null;
			}
			else
			{
				return child.gameObject;
			}
		}
		/// <summary>
		/// 查找名为name的GameObject,如果没有new一个
		/// </summary>
		/// <param name="name"></param>
		/// <param name="dontDestroyOnLoad"></param>
		/// <returns></returns>
		public static GameObject FindOrNew(string name,bool dontDestroyOnLoad = true)
		{
			var gobj = GameObject.Find(name);
			if(gobj == null)
			{
				gobj = new GameObject(name);
				if(dontDestroyOnLoad)
				{
					GameObject.DontDestroyOnLoad(gobj);
				}
			}
			return gobj;
		}
	}
}
